package edu.polsl.bio.str.node.messaging;

import edu.polsl.bio.str.common.messaging.StrJobPayload;
import edu.polsl.bio.str.node.delegate.DotPlotServiceDelegate;
import edu.polsl.bio.str.node.logic.ConnectionLossHandler;
import edu.polsl.bio.str.node.logic.DotPlotWorker;
import edu.polsl.bio.str.node.logic.NodeContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.channel.SubscribableChannel;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageDeliveryException;
import org.springframework.integration.message.MessageHandler;
import org.springframework.integration.message.MessageHandlingException;
import org.springframework.integration.message.MessageRejectedException;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;

/**
 * //todo class description
 * <p/>
 * Created on: Jun 12, 2011 12:40:44 AM <br/>
 * <a href="http://www.polsl.pl">www.polsl.pl</a>
 *
 * @author lukasz.olczak@polsl.pl
 */
public class JobHandler implements MessageHandler {
  /**
   * slf4j Logger.
   */
  private static final Logger log = LoggerFactory.getLogger(JobHandler.class.getName());

  private SubscribableChannel channel;

  private ExecutorService executor;

  private NodeContext nodeContext;

  private DotPlotServiceDelegate dotPlotServiceDelegate;

  private ConnectionLossHandler connectionLossHandler;

  @PostConstruct
  public void init() {
    channel.subscribe(this);
  }

  @Override
  public void handleMessage(Message<?> message) throws MessageRejectedException, MessageHandlingException, MessageDeliveryException {
    log.debug("Handled message: {}", message);
    if (!nodeContext.isAttached()) {
      log.error("Handled job payload when node was detached");
      throw new MessageRejectedException(message, "Node not attached");
    }
    DotPlotWorker worker = new DotPlotWorker((StrJobPayload) message.getPayload());
    worker.setDotPlotServiceDelegate(dotPlotServiceDelegate);
    worker.setNodeContext(nodeContext);
    worker.setConnectionLossHandler(connectionLossHandler);
    executor.execute(worker);
  }

  public void setChannel(SubscribableChannel channel) {
    this.channel = channel;
  }

  public void setExecutor(ExecutorService executor) {
    this.executor = executor;
  }

  public void setNodeContext(NodeContext nodeContext) {
    this.nodeContext = nodeContext;
  }

  public void setDotPlotServiceDelegate(DotPlotServiceDelegate dotPlotServiceDelegate) {
    this.dotPlotServiceDelegate = dotPlotServiceDelegate;
  }

  public void setConnectionLossHandler(ConnectionLossHandler connectionLossHandler) {
    this.connectionLossHandler = connectionLossHandler;
  }
}
